import axios from "axios"
import { ElLoading } from "element-plus"
import NProgress from "nprogress"
import "nprogress/nprogress.css"

NProgress.configure({ showSpinner: false })

let loading = null
let requestCount = 0

const showLoading = () => {
  if (requestCount === 0) {
    loading = ElLoading.service({
      lock: true,
      text: "加载中...",
      background: "rgba(0, 0, 0, 0.7)"
    })
  }
  requestCount++
}

const hideLoading = () => {
  requestCount--
  if (requestCount === 0 && loading) {
    loading.close()
    loading = null
  }
}

const http = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 10000
})

http.interceptors.request.use(
  config => {
    NProgress.start()
    showLoading()
    return config
  },
  error => {
    hideLoading()
    return Promise.reject(error)
  }
)

http.interceptors.response.use(
  response => {
    NProgress.done()
    hideLoading()
    return response.data
  },
  error => {
    NProgress.done()
    hideLoading()
    return Promise.reject(error)
  }
)

export default http
